const express = require('express')
const fs = require('fs')
const { promisify } = require('util')


const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
const app = express()
// app.use(express.urlencoded())  // content-type': 'application/x-www-form-urlencoded', 对应的请求内容类型
app.use(express.json())   // 对应的内容请求类型 'content-type': 'application/json',

app.get('/', async (req, res) => {
    try {
        const data = await readFile('./db.json', 'utf8')
        let jsonObj = JSON.parse(data) 
        res.send(jsonObj.users)
    } catch (error) {
        res.status(500).json({
            err: error,
            code: '500',
            msg: '系统异常'
        })
    }
})

app.post('/', async (req, res) => {
    console.log(req.headers)
    console.log(req.body)
    const body = req.body
    if(!body){
        res.status(500).json({
            err: '缺少请求参数',
            code: '400',
            msg: '缺少请求参数'
        })
    } else {
        try {
            const data = await readFile('./db.json', 'utf8')
            let jsonObj = JSON.parse(data) 
            body.id = jsonObj.users[jsonObj.users.length - 1].id + 1
            jsonObj.users.push(body)
            const w = await writeFile('./db.json', JSON.stringify(jsonObj))
            console.log('--w')
            console.log(w)
            if(!w){
                res.status(200).send({
                    code: '000',
                    msg: '添加成功'
                })
            } else {
                res.status(500).json({
                    err: error,
                    code: '500',
                    msg: '系统异常1'
                })
            }
        } catch (error) {
            res.status(500).json({
                err: error,
                code: '500',
                msg: '系统异常2'
            })
        }
    }
})

app.listen(7001, () => {
    console.log('Run http://127.0.0.1:7001')
})